class MainUI extends UIBase{
	public main_group:eui.Group;
	private Main_group:eui.Group;
	private item_group:eui.Group;

	private btn_box:BaseButton;

	public start_btn:eui.Image;
	private img_start:eui.Image;
	private img_bg:eui.Image;
	/**
	 * 技能
	 */
	private gold_lb:eui.Label;
	public  skill_number:eui.Group;
	private fish_number_bg_on:eui.Image;
	private fish_number_label:eui.Label;
	private fish_number:eui.Label;
	private fish_number_price:eui.Label;
	private fish_depth_bg_on:eui.Image;
	private skill_depth:eui.Group;
	private fish_depth_label:eui.Label;
	private fish_depth:eui.Label;
	private fish_depth_price:eui.Label;
	private fish_income_bg_on:eui.Image;
	private skill_income:eui.Group;
	private fish_income_label:eui.Label;
	private fish_income:eui.Label;
	private fish_income_price:eui.Label;
	public 	container:eui.Group;
	/**
	 * btn组
	 */
	private btn_sound:BaseButton;
	private btn_rank:BaseButton;
	private btn_tujian:BaseButton;
	// private btn_share:BaseButton;
	private btn_bg:BaseButton;
	private btn_task:BaseButton;

	/**
	 * 人物组合
	 */
	private img_man:eui.Image;
	private fish_hand:eui.Image;
	private lb_startGame:eui.Label;
	private hand_Gp:eui.Group;
	private fish_line_1:eui.Image;
	private fish_line_2:eui.Image;

	/**
	 * 云组合
	 */
	private could_1:eui.Image;

	private wave1:eui.Image;
	private wave2:eui.Image;
	private count:number;

	private _isSoundPlay:boolean = true;

	private FishPond:FishpondUI;
	private Timer = new egret.Timer(GameConst.fishUpTime);
	//当前结算的鱼的数据
	private CurAccountData;
	//当前结算到第几条鱼
	private CurAccountIndex = 0;

	//鱼塘
	public fish_pools:egret.MovieClip;

	private box_group:eui.Group;

	//banner广告
    public ad;

	public constructor() {
		super('MainView');
	}

	public init(){
		this.width = GlobalManager.instance().curWidth();
		this.height = GlobalManager.instance().curHeight();
		this.main_group.height = this.height;
		this.width = this.Main_group.width;
		this.count = 0;
		this.addBannerAd();

		this.initAnimation();
		if(!this.FishPond)
		{
			this.FishPond = FishpondUI.instance();
			this.FishPond.y = this.main_group.height;
			this.main_group.addChild(this.FishPond); 
		}
		this.fixIphoneX();

		// 获取数值并显示 -- 金钱、技能
		this.EnableSkill()

		this.gold_lb.text = RoleCache.instance().getGoldLb()
		this.fish_number.text = RoleCache.instance().getFishNumber() + ' 条'
		this.fish_number_price.text = '$' + RoleCache.instance().getFishNumberPrice()
		if(RoleCache.instance().getFishDepth() >= GameConst.FishPondMaxDepth)
		{
			this.fish_depth.text = '已经到达了最大深度';
		}
		else
		{
			this.fish_depth.text = RoleCache.instance().getFishDepth() + ' 米'
			this.fish_depth_price.text = '$ ' + RoleCache.instance().getFishDepthPrice()
		}
		this.setFishIncome();
		// this.fish_income_price.text = '$ ' + RoleCache.instance().getFishIncomePrice()

		// 播放背景音乐
		SoundManager.instance().playMainSound();

		if(RoleCache.instance().reviewStatus)
        {
            this.box_group.visible = false;
        }
		// this.touchChildren = false;

		// if(RoleCache.instance().openid)
		// {
		// 	//离线收益 等待界面打开
		// 	egret.setTimeout(()=>{
		// 		if(RoleCache.instance().offlineMoney && RoleCache.instance().offlineMoney > 0)
		// 		{
		// 			let data = {};
		// 			data['isPop'] = true;
		// 			data['type'] = AccountType.OFFLINE;
		// 			UIManager.instance().openUILogic(AccountUI, data);
		// 		}
		// 		else
		// 		{
		// 			this.touchChildren = true;
		// 		}
		// 	},this, 500);
		// }
		// else
		// {
		// 	this.touchChildren = true;
		// }

		this.initNewUserGuide();

		this.addFishPools();
	}

	public setFishIncome()
	{
		this.fish_income.text = Math.floor(RoleCache.instance().fishIncome) + ' / 时'
	}

	public addFishPools()
	{
		if(!this.fish_pools)
		{
			let mcDataFactory: egret.MovieClipDataFactory
                = new egret.MovieClipDataFactory(RES.getRes("fish_move_json"), RES.getRes("fish_move_png"));
            this.fish_pools = new egret.MovieClip(mcDataFactory.generateMovieClipData('欢乐鱼塘'));
            this.skill_income.addChild(this.fish_pools);
			this.fish_pools.x = this.skill_income.width - this.fish_pools.width >> 1;
			this.fish_pools.y = 0;
			this.fish_pools.play(-1);
		}
	}

	public addBannerAd()
    {
		if(!this.ad)
			this.ad = WeChatgGameManager.instance().showBannerAd(GameConst.adList.bottom_banner);
        if(this.ad)
        {
            this.ad.show();
        }
    }

	//隐藏广告
    public hideAd()
    {
        if(this.ad)
        {
            this.ad.hide().then(()=>{
                // this.ad = null;
            });
        }
    }

	//初始化动画写在这里
	protected initAnimation()
	{
		this.CouldAnimation();
		this.roleAnimation();
		this.woldAnimation();
		//水波的动画事件
		egret.startTick(this.waveAnimation,this);
		EffectUtil.instance().shakeEffect(this.btn_box);
	}

	//获取随机背景id
	public getRandomBg()
	{
		let index : number = Math.random() * GameConst.GameBgMaxId << 0;
		if(index == 0)
			index = 6
		return index;
	}

	//白云的动画
	private CouldAnimation()
	{
		let self = this;
		// EffectUtil.instance().StopEffect(this.could_2);
		EffectUtil.instance().StopEffect(this.could_1);
		// self.could_2.alpha = 0.6;
		let time = 5000;
		// let call1 = function(){
		// 	egret.Tween.get(self.could_2).to({
		// 		x : self.width + self.could_2.width
		// 	}, time).wait(500).call(()=>{
		// 		time = 10000;
		// 		self.could_2.x = -self.could_2.width - 50;
		// 		call1.call(self);
		// 	})
		// }
		let call2 = function(){
			egret.Tween.get(self.could_1).to({
				x : -self.could_1.width - 50
			}, 8000).wait(500).call(()=>{
				self.could_1.x = self.width + self.could_1.width;
				call2.call(self);
			})
		}
		// call1();
		call2();
	}

	//人物的动画
	private roleAnimation()
	{
		EffectUtil.instance().StopEffect(this.img_man);
		EffectUtil.instance().StopEffect(this.hand_Gp);
		EffectUtil.instance().flyObj(this.img_man,2000, 20);
		EffectUtil.instance().flyObj(this.hand_Gp,2000, 20);
	}

	//字的动画
	private woldAnimation()
	{
		EffectUtil.instance().StopEffect(this.lb_startGame);
		EffectUtil.instance().ScaleEffect(this.lb_startGame);
	}

	private stopAllAnimation()
	{
		//恢复初始位置及大小
		this.lb_startGame.alpha = 1;
		this.lb_startGame.scaleX = this.lb_startGame.scaleY = 1;
		this.img_man.y = 157;
		// this.fish_hand.y = 268;
		this.hand_Gp.y = 280;
		// EffectUtil.instance().StopEffect(this.could_2);
		EffectUtil.instance().StopEffect(this.could_1);
		EffectUtil.instance().StopEffect(this.lb_startGame);
		EffectUtil.instance().StopEffect(this.img_man);
		EffectUtil.instance().StopEffect(this.hand_Gp);
		//水波的动画事件
		egret.stopTick(this.waveAnimation,this);
		this.btn_box.rotation = 0;
		EffectUtil.instance().StopEffect(this.btn_box);

		this.hideAd();
	}

	protected addEvent(){
		GameUtil.addEventListener(EventConst.ACCOUNT_EVENT,this.Account, this);
		GameUtil.addEventListener(EventConst.RESOURCE_CHANGED,this.UpdateMoney, this);
		// 开始游戏按钮 => 绑定startGame事件
		this.start_btn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.startGame, this);
		// 技能模块绑定事件
		this.skill_number.addEventListener(egret.TouchEvent.TOUCH_TAP, this.updateNumber, this)

		this.skill_depth.addEventListener(egret.TouchEvent.TOUCH_TAP, this.updateDepth, this)

		this.skill_income.addEventListener(egret.TouchEvent.TOUCH_TAP, this.GotoFishPools, this)
		
		//  声音按钮绑定事件
		this.btn_sound.addTapHandler(this.soundSwitch,this);

		// 排行榜按钮绑定事件
		this.btn_rank.addTapHandler(this.btnRankHandle,this);

		// 分享按钮绑定事件
		// this.btn_share.addTapHandler(this.share, this);

		// 图鉴按钮
		this.btn_tujian.addTapHandler(this.btnTujianHandle, this);

		// 背景切换按钮
		// this.btn_bg.addTapHandler(this.changeBg,this);

		// 任务按钮绑定事件
		this.btn_task.addTapHandler(this.btnTaskHandle, this);

		//监听结算钓鱼事件
		this.Timer.addEventListener(egret.TimerEvent.TIMER, this.FishAccount, this);

		//精品盒子
		this.btn_box.addTapHandler(this.jumpToBox,this);
	}

	public jumpToBox()
	{
		// WeChatgGameManager.instance().navigateToMiniProgram();
		let data = {
            isPop:true,
            showBG:true,
            effect:3
        }
        UIManager.instance().openUILogic(BoxUI,data);
	}

	public waveAnimation()
	{
		this.count++;
		if(this.count % 3 != 0)
			return false;
		this.count = 0;
		this.wave1.x -= GameConst.WaterMoveSpeed;
		if(this.wave1.x <= -this.wave1.width){
			this.wave1.x = this.width;
		}
		this.wave2.x -= GameConst.WaterMoveSpeed;
		if(this.wave2.x <= -this.wave2.width){
			this.wave2.x = this.width;
		}
		return true;
	}

	//变更资源数据
	protected UpdateMoney()
	{
		let curMoney = this.gold_lb.text;
		let money = RoleCache.instance().getGoldLb();
		EffectUtil.instance().NumChange(this.gold_lb, parseInt(curMoney), money, 500);
		this.EnableSkill();

		if(!GuideCache.instance().getGuideStatusByIdAndSubId(1,3))
		{
			//尚未完成第三个引导
			let data = {
				curGuideId:1,
				curGuideSubId:3
			}
			GuideManager.instance().showGuide(data);
		}
	}

	public restartGame()
	{
		this.start_btn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.startGame, this);
		this.lb_startGame.visible = true;
		this.touchChildren = true;
		this.initAnimation();
		this.addBannerAd();
	}

	public btnRankHandle()
	{
		UIManager.instance().openUILogic(RankListUI,{isPop:true});
	}

	public btnTujianHandle()
	{
		UIManager.instance().openUILogic(TujianUI,{isPop:true, effect:3});
	}

	public changeBg()
	{
		let source = this.img_bg.source.toString();
		let curId = parseInt(source.split('_')[2]);
		if(curId == GameConst.GameBgMaxId)
		{
			curId = 1;
		}
		else
		{
			curId ++ ;
		}
		this.img_bg.source = 'main_bg_'+curId+'_jpg';
		MessageUtil.tips('切换成功');
	}

	public btnTaskHandle(){
		UIManager.instance().openUILogic(TaskListUI,{isPop:true})
	}

	// 获取倍数
	public getMultiple(){
		HttpManager.instance().sendPost(GameConst.httpUrl + 'options/set_multiple', '' , (e)=>{
            let data = JSON.parse(e)
			
			if(data.data.multiple){
				RoleCache.instance().data.multiple = data.data.multiple
				// RoleCache.instance().data.isVideo = data.data.isVideo
			}
			
        } , this)
	}

	//结算
	public Account(e)
	{
		let parma = e.param.data;
		if(parma)
		{
			egret.Tween.get(this.fish_line_1).to({
				// 手臂上挥
				rotation:-60
			}, 50).call(()=>{
				this.fish_line_1.visible = false;
				this.fish_line_2.visible = true;
				this.fish_line_1.rotation = 0;
			});
			egret.Tween.get(this.hand_Gp).to({
				// 手臂上挥
				rotation:-60
			}, 50).call(()=>{
				egret.Tween.get(this.hand_Gp).to({
					// 手臂下挥
					rotation:-30
				}, 500).call(()=>{
					this.fish_line_2.visible = false;
					this.fish_line_1.visible = true;
				}).to({
					rotation:0
				},500);
				// UIManager.instance().openUILogic(AccountUI, data);
				this.CurAccountData = parma;
				this.StartFishAccountAnimation();
			});
		}
	}

	private StartFishAccountAnimation()
	{
		this.touchChildren = false;
		if(this.CurAccountData.length > 0)
		{
			let fish = this.CurAccountData[this.CurAccountIndex];
			let item:FishItem = FishItemPool.getOneFishItem(fish);
			this.addChild(item);
			item.x = this.width - item.width >> 1;
			item.y = this.height - item.height - 200;
			item.Move();
			this.CurAccountIndex ++ ;
			this.Timer.start();
		}
		else
		{
			let data = {};
			data['data'] = this.CurAccountData;
			data['isPop'] = true;
			data['type'] = AccountType.NORMAL;
			UIManager.instance().openUILogic(AccountUI, data);
		}
	}

	//定时器走的函数
	private FishAccount()
	{
		if(this.CurAccountData.length > this.CurAccountIndex)
		{
			let fish = this.CurAccountData[this.CurAccountIndex];
			let item:FishItem = FishItemPool.getOneFishItem(fish);
			this.addChild(item);
			item.x = this.width - item.width >> 1;
			item.y = this.height - item.height - 200;
			item.Move();
			this.CurAccountIndex ++ ;
		}
		else
		{
			this.Timer.reset();
			egret.setTimeout(()=>{
				let data = {};
				data['data'] = this.CurAccountData;
				data['isPop'] = true;
				data['type'] = AccountType.NORMAL;
				UIManager.instance().openUILogic(AccountUI, data);
				this.CurAccountIndex = 0;
				this.CurAccountData = [];
			},this, 500);
		}
	}

	/**
	 * 点击开始游戏
	 */
	protected startGame()
	{
		if(GuideManager.instance().judgeIsInGuide(1,1))
		{
			GuideManager.instance().hideGuide();
			GuideManager.instance().postGuideStepChange();
			GuideCache.instance().SaveGuideProcessByIdAndSubId(1,1);
		}
		this.start_btn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.startGame, this);
		this.stopAllAnimation();
		// 挥臂动画
		this.moveHand();
		this.lb_startGame.visible = false;
		//
		this.getMultiple();
	}

	/**
	 * 升级技能
	 */
	protected updateNumber(){
		// 检查剩余持有金钱是否够升级
		if(RoleCache.instance().data.money >= RoleCache.instance().data.count.next_pay)
			SkillPrase.instance().updateFishNumber(this.updateScene, this);
		else
			MessageUtil.tips("金币不足");
	}
	protected updateDepth(){
		if(RoleCache.instance().getFishDepth() >= GameConst.FishPondMaxDepth)
		{
			MessageUtil.tips("已经达到了最大深度");
			return ;
		}
		// 检查剩余持有金钱是否够升级
		if(RoleCache.instance().data.money >= RoleCache.instance().data.depth.next_pay)
			SkillPrase.instance().updateFishDepth(this.updateScene, this);
		else
			MessageUtil.tips("金币不足");
	}
	protected updateIncome(){
		// 检查剩余持有金钱是否够升级
		// if(RoleCache.instance().data.money >= RoleCache.instance().data.offline.next_pay)
		// 	SkillPrase.instance().updateFishOffline(this.updateScene, this);
		// else
		// 	MessageUtil.tips("金币不足");
	}

	protected GotoFishPools()
	{
		let data = {
			isPop:true,
			effect:7
		}
		UIManager.instance().openUILogic(FishPoolsUI, data);
	}

	// 更新游戏界面 --- 持有金钱、技能等级、升级技能所需金钱
	public updateScene(data){
		let type = data.type
		switch (type){
			case 'count':
				this.fish_number.text = data.count.num + ' 条'
				this.fish_number_price.text = '$ ' + RoleCache.instance().getFishNumberPrice()
				break;
			case 'depth':
				if(data.depth.num >= GameConst.FishPondMaxDepth)
				{
					this.fish_depth.text = '已经到达了最大深度';
				}	
				else
				{
					this.fish_depth.text = data.depth.num + ' 米'
					this.fish_depth_price.text = '$ ' + RoleCache.instance().getFishDepthPrice()
				}
				break;
			case 'offline':
				this.fish_income.text = data.offline.num + ' / 时'
				// this.fish_income_price.text = '$ ' + RoleCache.instance().getFishIncomePrice()
				break;
		}
		MessageUtil.tips('升级成功');
	}

	// 技能变灰 --- 禁止点击升级
	public EnableSkill(){
		let change = function(img_bg:eui.Image, label1:eui.Label, label2:eui.Label, label3:eui.Label, isOn)
		{
			img_bg.source = isOn ? "skill_on_png" : "skill_off_png";
			// label1.textColor = isOn ? 0x784600 : 0x373737;
			// label2.textColor = isOn ? 0x784600 : 0x373737;
			label3.textColor = isOn ? 0xDB8E1A : 0x373737;
		}

		change(this.fish_number_bg_on, this.fish_number_label, this.fish_number, this.fish_number_price ,
			   RoleCache.instance().data.money >= RoleCache.instance().data.count.next_pay);

		let depthJudge = RoleCache.instance().getFishDepth() < GameConst.FishPondMaxDepth;
		let depthMoneyJudge = RoleCache.instance().data.money >= RoleCache.instance().data.depth.next_pay;
		change(this.fish_depth_bg_on, this.fish_depth_label, this.fish_depth, this.fish_depth_price ,
			  depthJudge && depthMoneyJudge);

		// change(this.fish_income_bg_on, this.fish_income_label, this.fish_income, this.fish_income_price ,
		// 	   RoleCache.instance().data.money >= RoleCache.instance().data.offline.next_pay);
	}

	// 挥臂下杆
	protected moveHand(){
		this.FishPond.InitGame();
		egret.Tween.get(this.fish_line_1).to({
			rotation:40
		},500);
		egret.Tween.get(this.hand_Gp).to({
			// 手臂上挥
			rotation:-45
		}, 500).call(()=>{
			this.fish_line_1.visible = false;
			this.fish_line_2.visible = true;
			this.fish_line_1.rotation = 0;
			egret.Tween.get(this.hand_Gp).to({
				// 手臂下挥
				rotation:0
			}, 200).call(()=>{
				// 场景切换
				this.fish_line_1.visible = true;
				this.fish_line_2.visible = false;
				this.moveBg();
			})
		});
	}
	//移动背景
	protected moveBg()
	{
		egret.Tween.get(this.main_group).to({
			y:-this.height
		}, 100).call(()=>{
			this.FishPond.moveBg();
		});
	}

	// 声音开关
	protected soundSwitch(){
		if(this._isSoundPlay){
			// 关声音
			this._isSoundPlay = false;
			SoundManager.instance().stop();
			this.btn_sound.currentState = "off";
		}else{
			// 开声音
			this._isSoundPlay = true
			SoundManager.instance().playMainSound();
			this.btn_sound.currentState = "on";
		}
	}

	protected initNewUserGuide()
    {   
        if(!GuideCache.instance().getGuideStatusByIdAndSubId(1,1))
        {
            let data = {
                curGuideId : 1,
                curGuideSubId : 1
            }
            GuideManager.instance().showGuide(data)
        }
    }

	// 分享
	protected share(){
		SharePrase.instance().requestOneAdvertisement({type:ShareId.default});
	}

	//屏幕适配x
    protected fixIphoneX()
    {
		if(GlobalManager.instance().isIphonex())
		this.Main_group.top = Math.floor(GlobalManager.instance().curHeight()/34);
    }

	protected removeEvent(){
		this.main_group.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.startGame, this);
		this.skill_number.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.updateNumber, this)
		this.skill_depth.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.updateDepth, this)
		this.skill_income.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.GotoFishPools, this)
		this.Timer.removeEventListener(egret.TimerEvent.TIMER,this.FishAccount,this);
		GameUtil.removeEventListener(EventConst.RESOURCE_CHANGED, this.UpdateMoney, this);
		// this.btn_share.removeTapHandler();
		this.btn_rank.removeTapHandler();
		this.btn_sound.removeTapHandler();
		this.btn_bg.removeTapHandler();
		this.btn_tujian.removeTapHandler();
		this.btn_task.removeTapHandler();
		this.btn_box.removeTapHandler();
		egret.stopTick(this.waveAnimation,this);
	}

	protected clear(){
		super.clear();
		this.CurAccountData = null;
		this.CurAccountIndex = null;
	}
}